package npr;


import processing.core.*;

import javax.media.opengl.*;
import com.sun.opengl.util.*;

import java.lang.RuntimeException;

/**
 * A per-pixel diffuse shader. It does not take into account light colors and material properties,
 * but is sufficient for many NPR applications. Material properties, ambient lights an specular highlights
 * can be simulated using a look-up table.
 */
public class DiffuseShader extends Shader{


    protected LookUpTable lut;
    protected int lutID[];

    /**
     * Creates a DiffuseShader object and inizializes it.
     */
    public DiffuseShader(){
	
	renderer= (NPR)parent.g;
	gl= renderer.gl;
	lutID= new int[1];
        gl.glGenTextures(1, lutID, 0);
    }

    /**
     * Attaches a look-up table to the shader.
     *
     * @see LookUpTable
     * 
     * @param lut the look-up table to use with the shader.
     */ 
    public void setLookUpTable(LookUpTable lut){
	this.lut= lut;
    }

    /**
     * Sets the state of the main shader
     */
    protected void prepare(){

	renderer= (NPR)parent.g;
	gl= renderer.gl;
	
	if(lut!=null){
	    
	    gl.glActiveTexture(GL.GL_TEXTURE0);
	    gl.glBindTexture(GL.GL_TEXTURE_2D, lutID[0]);
	    gl.glTexParameteri (GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST);	
	    gl.glTexParameteri (GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST);
	    gl.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_LUMINANCE, 256, 1, 0, GL.GL_LUMINANCE_ALPHA, GL.GL_UNSIGNED_BYTE, lut.get());
	    
	    renderer.setBoolean("useLookUpTable", true);
	}    

	renderer.setBoolean("cel", true);
	renderer.setInteger("lightCountInt", renderer.lightCount);
	renderer.setFloat("lightCountFloat", (float)renderer.lightCount);
	for(int i= 0; i< renderer.lightCount; i++){
	    renderer.setInteger("lightType[" + i + "]", renderer.lightType[i]);
	}
    }

    /**
     * Resets the OpenGL state set in prepare()
     */
    protected void cleanUp(){
	renderer= (NPR)parent.g;
	gl= renderer.gl;
	gl.glActiveTexture(GL.GL_TEXTURE0);
    }
}
